"""
使用S50观测T_CRB的图形程序
"""

import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW

#!/usr/bin/python

# import subprocess
import threading
# from threading import Thread
# from multiprocessing import Process
import subprocess
# import signal
import time
import configparser
# import sys
import os
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW

# import asyncio
# import tcrbseestar
# import setproctitle
# setproctitle.setproctitle("用S50监测T_CrB")
# 全局变量
GLOBAL_DEFAULT_配置文件名 = r'.\S50.ini'
GLOBAL_FLAG_是否是长期观测站 = False
GLOBAL_DEFAULT_CONST_长期观测站默认值='TE011'
GLOBAL_DEFAULT_CONST_临时观测站默认值='T_S50'
GLOBAL_DEFAULT_观测站ID = r'观测站编号：长期编号以TE/TW开头，临时观测以"T_S50"开头'
GLOBAL_DEFAULT_个人标识ID = r'个人标识信息：如邮箱或者手机号，长度截断11个字符再上报'
GLOBAL_观测站和个人标识 = f'{GLOBAL_DEFAULT_观测站ID}{GLOBAL_DEFAULT_个人标识ID}'
GLOBAL_DEFAULT_TCRB赤经RA = r'16.0110166536569'
GLOBAL_DEFAULT_TCRB赤纬DEC = r'25.8569291498168'
GLOBAL_DEFAULT_拍摄exe文件名 = r'C:\S50TCrB_ALLinOne_GUI\bin\tcrbcapturer.exe'
GLOBAL_DEFAULT_转存exe文件名 = r'C:\S50TCrB_ALLinOne_GUI\bin\tcrbtransfer.exe'
GLOBAL_DEFAULT_计算上报exe文件名 = r'C:\S50TCrB_ALLinOne_GUI\bin\tcrbuploader.exe'
GLOBAL_DEFAULT_拍摄时长 = r'21600'
GLOBAL_DEFAULT_S50设备IP = r"192.168.0.2"  # 默认值
GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录 = r".\S50拍摄T_CrB的fit文件目录"  # 默认值
GLOBAL_DEFAULT_输出文件夹转存计算上报目录 = r".\转存到硬盘目录"  # 默认值
GLOBAL_DEFAULT_转存计算上报轮询间隔 = 30
GLOBALINFOLABEL_长期观测站提示 = '长期观测无需填写个人识别信息，请找高老师申请TE/TW开头编号'
GLOBALINFOLABEL_临时观测站提示 = "临时观测写能标识身份的尽量短信息，上报程序会删除特殊符号并截止前10个字符"

class tcrb_S50_gui(toga.App):
    def __init__(self):
        super().__init__(formal_name="用S50拍摄T CrB的控制程序", app_id="com.seestar.tcrb.s50")
        self.ip_input_str = GLOBAL_DEFAULT_S50设备IP
        self.thread_flag_capture = False
        self.thread_flag_transfer = False
        self.thread_flag_report = False

    def startup(self):
        self.main_box = toga.Box(style=Pack(direction=COLUMN))
        # TCRB基本情况
        tcrb_info_lable = toga.Label(
            f"S50观测T_CrB：（{GLOBAL_DEFAULT_TCRB赤经RA},{GLOBAL_DEFAULT_TCRB赤纬DEC}）,增益为10。                            ")
        self.is_longterm_station_switch = toga.Switch(text="是否可以长期观测", value=True,
                                                      on_change=self.onchange_is_longterm_station_switch)
        tcrb_info_box = toga.Box(
            children=[tcrb_info_lable, self.is_longterm_station_switch],
            style=Pack(direction=ROW)
        )
        self.main_box.add(tcrb_info_box)
        # 配置文件部分
        self.config_file_input = toga.TextInput(
            value=GLOBAL_DEFAULT_配置文件名,
            style=Pack(flex=1)
        )
        load_config_button = toga.Button("选择配置文件", on_press=self.load_config)
        save_config_button = toga.Button("保存配置文件", on_press=self.save_config)

        config_box = toga.Box(
            children=[self.config_file_input, load_config_button, save_config_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(config_box)
        # 设置config_stationID设置部分
        self.station_id_input = toga.TextInput(value=GLOBAL_DEFAULT_观测站ID, style=Pack(flex=1))
        apply_station_id_button = toga.Button("应用", on_press=self.apply_config_station_id)
        station_id_label = toga.Label("S50观测站编号")
        station_box = toga.Box(
            children=[self.station_id_input, station_id_label, apply_station_id_button],
            style=Pack(direction=ROW)
        )

        self.main_box.add(station_box)
        # 设置个人身份ID设置部分
        # self.person_id_input = toga.TextInput(value=GLOBAL_DEFAULT_PERSON_ID, style=Pack(flex=1))
        if GLOBAL_FLAG_是否是长期观测站:
            self.person_id_input = toga.TextInput(value='', style=Pack(flex=1), readonly=True)
            self.person_id_input.value = ''
            self.person_id_input.readonly = True
            self.station_id_label = toga.Label(GLOBALINFOLABEL_长期观测站提示)
        else:
            self.person_id_input = toga.TextInput(value=GLOBAL_DEFAULT_个人标识ID, style=Pack(flex=1), readonly=False)
            self.person_id_input.value = GLOBAL_DEFAULT_个人标识ID
            self.person_id_input.readonly = False
            self.station_id_label = toga.Label(GLOBALINFOLABEL_临时观测站提示)
        self.temp_station_box = toga.Box(
            children=[self.person_id_input, self.station_id_label],
            style=Pack(direction=ROW)
        )
        self.main_box.add(self.temp_station_box)

        # 拍摄线程设置部分
        # self.ip_input = toga.TextInput(hint_text="目标设备IP", style=Pack(flex=1))
        self.ip_input = toga.TextInput(value=GLOBAL_DEFAULT_S50设备IP, style=Pack(flex=1))
        apply_ip_button = toga.Button("应用S50设备IP", on_press=self.apply_config_ip)
        capture_box = toga.Box(
            children=[self.ip_input, apply_ip_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(capture_box)

        # input文件夹设置box
        self.input_path_togatext = toga.TextInput(value=GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录, style=Pack(flex=1))
        apply_input_button = toga.Button("应用", on_press=self.apply_config_input)
        input_button = toga.Button("选择输入文件夹", on_press=self.choose_input_folder)
        config_input_folder_box = toga.Box(
            children=[self.input_path_togatext, input_button, apply_input_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(config_input_folder_box)
        # output文件夹设置box
        self.output_path_togatext = toga.TextInput(value=GLOBAL_DEFAULT_输出文件夹转存计算上报目录, style=Pack(flex=1))
        apply_output_button = toga.Button("应用", on_press=self.apply_config_output)
        output_button = toga.Button("选择输出文件夹", on_press=self.choose_output_folder)
        config_output_folder_box = toga.Box(
            children=[self.output_path_togatext, output_button, apply_output_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(config_output_folder_box)
        # 等待时间设置box
        self.waittime_togatext = toga.TextInput(value=GLOBAL_DEFAULT_转存计算上报轮询间隔, style=Pack(flex=1))
        capture_waittime_label = toga.Label("转存、计算和上报的间隔（秒）")
        config_wattime_button = toga.Button("应用", on_press=self.apply_config_waittime)
        config_waittime_box = toga.Box(
            children=[self.waittime_togatext, capture_waittime_label, config_wattime_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(config_waittime_box)
        # 拍摄exe
        self.exename_capture_togatext = toga.TextInput(value=GLOBAL_DEFAULT_拍摄exe文件名, style=Pack(flex=1))
        config_exename_capture_button = toga.Button("应用", on_press=self.apply_config_exename_duration_capture)  #需要补充拍摄时长设置
        choose_exe_capture_button = toga.Button("选择拍摄exe", on_press=self.choose_exe_capture_file)
        config_exename_capture_box = toga.Box(
            children=[self.exename_capture_togatext, choose_exe_capture_button, config_exename_capture_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(config_exename_capture_box)
        # 拍摄启停控制box
        self.capture_duration_togatext = toga.TextInput(value=GLOBAL_DEFAULT_拍摄时长, style=Pack(flex=1))
        capture_duration_label = toga.Label("拍摄时长（秒）")
        capture_duration_box = toga.Box(
            children=[self.capture_duration_togatext, capture_duration_label],
            style=Pack(direction=ROW)
        )
        self.main_box.add(capture_duration_box)
        capture_start_button = toga.Button("启动拍摄", on_press=self.start_capture_thread)
        capture_stop_button = toga.Button("停止拍摄", on_press=self.stop_capture_thread)
        capture_box = toga.Box(
            children=[capture_start_button, capture_stop_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(capture_box)
        # 转存exe
        self.exename_transfer_togatext = toga.TextInput(value=GLOBAL_DEFAULT_转存exe文件名, style=Pack(flex=1))
        config_exename_transfer_button = toga.Button("应用", on_press=self.apply_config_exename_transfer)
        choose_exe_transfer_button = toga.Button("选择转存exe", on_press=self.choose_exe_transfer_file)
        config_exename_transfer_box = toga.Box(
            children=[self.exename_transfer_togatext, choose_exe_transfer_button, config_exename_transfer_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(config_exename_transfer_box)
        transfer_start_button = toga.Button("启动转存", on_press=self.start_transfer_thread)
        transfer_stop_button = toga.Button("停止转存", on_press=self.stop_transfer_thread)
        transfer_box = toga.Box(
            children=[transfer_start_button, transfer_stop_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(transfer_box)
        # 计算上报exe
        self.exename_reporter_togatext = toga.TextInput(value=GLOBAL_DEFAULT_计算上报exe文件名, style=Pack(flex=1))
        config_exename_reporter_button = toga.Button("应用", on_press=self.apply_config_exename_reporter)
        choose_exe_reporter_button = toga.Button("选择计算上报exe", on_press=self.choose_exe_reporter_file)
        config_exename_reporter_box = toga.Box(
            children=[self.exename_reporter_togatext, choose_exe_reporter_button, config_exename_reporter_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(config_exename_reporter_box)
        report_start_button = toga.Button("启动上报", on_press=self.start_report_thread)
        report_stop_button = toga.Button("停止上报", on_press=self.stop_report_thread)
        report_box = toga.Box(
            children=[report_start_button, report_stop_button],
            style=Pack(direction=ROW)
        )
        self.main_box.add(report_box)

        # 全部启动和停止按钮
        apply_settings_button = toga.Button("全部应用", on_press=self.apply_all_settings_s50)
        all_start_button = toga.Button("全部启动", on_press=self.start_all_threads)
        all_stop_button = toga.Button("全部停止", on_press=self.stop_all_threads)
        self.main_box.add(apply_settings_button)
        self.main_box.add(all_start_button)
        self.main_box.add(all_stop_button)

        # 输出信息文本框
        self.output_area = toga.MultilineTextInput(readonly=True, style=Pack(flex=1))
        clear_output_area = toga.Button("清除日志", on_press=self.clear_all_logs)
        self.main_box.add(self.output_area)
        self.main_box.add(clear_output_area)

        self.main_window = toga.MainWindow(title=self.formal_name)
        self.main_window.content = self.main_box
        # self.main_window.show()
        self.print_config()
        self.main_window.show()
        # 默认加载配置文件，没做完，不过也凑合能用就算了哈
        # self.load_config_or_default()

    def output_message(self, message):
        """将消息输出到文本框"""
        self.output_area.scroll_to_bottom()
        self.output_area.value += message
        self.output_area.scroll_to_bottom()

    def print_config(self):
        # global GLOBAL_DEFAULT_STATION_ID,GLOBAL_DEFAULT_DEVICE_IP, GLOBAL_DEFAULT_WAITTIME, GLOBAL_DEFAULT_INPUT_FOLDER, GLOBAL_DEFAULT_OUTPUT_FOLDER
        self.output_message(f"-----------所有设置打印开始---------\n")
        #                     f"#观测的ID:{GLOBAL_DEFAULT_STATION_ID}\n"
        #                     f"#设备的IP: {GLOBAL_DEFAULT_DEVICE_IP}\n"
        #                     f"#输入目录: {GLOBAL_DEFAULT_INPUT_FOLDER}\n"
        #                     f"#输出目录: {GLOBAL_DEFAULT_OUTPUT_FOLDER}\n"
        #                     f"#轮训间隔:{GLOBAL_DEFAULT_WAITTIME}\n"

        for i in globals():
            if i.startswith('GLOBAL_'):
                self.output_message(f"{i}:{globals()[i]}\n")
        self.output_message(f"-----------所有设置打印完成---------\n")

    def onchange_is_longterm_station_switch(self, widget):
        global GLOBAL_FLAG_是否是长期观测站
        if self.is_longterm_station_switch.value == True:
            self.person_id_input.value = ''
            self.person_id_input.readonly = True
            self.station_id_label.text = GLOBALINFOLABEL_长期观测站提示
            self.station_id_input.value = GLOBAL_DEFAULT_观测站ID
            self.station_id_input.readonly = False
            GLOBAL_FLAG_是否是长期观测站 = True
            GLOBAL_观测站和个人标识 = GLOBAL_DEFAULT_观测站ID
            self.station_id_label.refresh()
        else:
            self.person_id_input.value = GLOBAL_DEFAULT_个人标识ID
            self.person_id_input.readonly = False
            self.station_id_label.text = GLOBALINFOLABEL_临时观测站提示
            self.station_id_input.value = GLOBAL_DEFAULT_CONST_临时观测站默认值
            self.station_id_input.readonly = True
            GLOBAL_FLAG_是否是长期观测站 = False
            GLOBAL_观测站和个人标识 = GLOBAL_DEFAULT_CONST_临时观测站默认值 + GLOBAL_DEFAULT_个人标识ID
            self.station_id_label.refresh()

    def apply_config_station_id(self, widget):
        global GLOBAL_DEFAULT_观测站ID, GLOBAL_DEFAULT_个人标识ID,GLOBAL_观测站和个人标识
        GLOBAL_DEFAULT_观测站ID = self.station_id_input.value
        GLOBAL_DEFAULT_个人标识ID = self.person_id_input.value
        GLOBAL_观测站和个人标识 = f"{GLOBAL_DEFAULT_观测站ID}{GLOBAL_DEFAULT_个人标识ID}"
        self.output_message(f"设置观测站上传编号为:{GLOBAL_观测站和个人标识}\n")

    def apply_config_ip(self, widget):
        global GLOBAL_DEFAULT_S50设备IP
        GLOBAL_DEFAULT_S50设备IP = self.ip_input.value
        self.output_message(f"正在设置_S50的IP为:{GLOBAL_DEFAULT_S50设备IP}\n")

    def apply_config_input(self, widget):
        global GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录
        GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录 = self.input_path_togatext.value
        self.output_message(f"正在设置_fit文件读取输入目录为:{GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录}\n")

    def apply_config_output(self, widget):
        global GLOBAL_DEFAULT_输出文件夹转存计算上报目录
        GLOBAL_DEFAULT_输出文件夹转存计算上报目录 = self.output_path_togatext.value
        self.output_message(f"正在设置_转存输出目录为:{GLOBAL_DEFAULT_输出文件夹转存计算上报目录}\n")

    def apply_config_waittime(self, widget):
        global GLOBAL_DEFAULT_转存计算上报轮询间隔
        GLOBAL_DEFAULT_转存计算上报轮询间隔 = self.waittime_togatext.value
        self.output_message(f"正在设置_轮训间隔为:{GLOBAL_DEFAULT_转存计算上报轮询间隔}\n")

    def apply_config_exename_duration_capture(self, widget):
        global GLOBAL_DEFAULT_拍摄exe文件名,GLOBAL_DEFAULT_拍摄时长
        GLOBAL_DEFAULT_拍摄exe文件名 = self.exename_capture_togatext.value
        GLOBAL_DEFAULT_拍摄时长 = self.capture_duration_togatext.value
        self.output_message(
            f"正在设置_拍摄exe为:{GLOBAL_DEFAULT_拍摄exe文件名},拍摄时长{GLOBAL_DEFAULT_拍摄时长}秒\n")

    def apply_config_exename_transfer(self, widget):
        global GLOBAL_DEFAULT_转存exe文件名
        GLOBAL_DEFAULT_转存exe文件名 = self.exename_transfer_togatext.value
        self.output_message(f"正在设置_转存exe为:{GLOBAL_DEFAULT_转存exe文件名}\n")

    def apply_config_exename_reporter(self, widget):
        global GLOBAL_DEFAULT_计算上报exe文件名
        GLOBAL_DEFAULT_计算上报exe文件名 = self.exename_reporter_togatext.value
        self.output_message(f"正在设置_计算上报exe为:{GLOBAL_DEFAULT_计算上报exe文件名}\n")

    def apply_stationid_personid(self, widget):
        pass

    def apply_all_settings_s50(self, widget):
        self.apply_config_station_id(widget)
        self.apply_config_ip(widget)
        self.apply_config_input(widget)
        self.apply_config_output(widget)
        self.apply_config_waittime(widget)
        self.apply_config_exename_duration_capture(widget)
        self.apply_config_exename_reporter(widget)
        self.apply_config_exename_transfer(widget)
        self.output_message(f"所有应用设置如下:\n")
        self.print_config()

    def load_config_or_default(self):
        """加载默认配置文件或使用全局变量---其实没有实现，凑合用吧"""
        global GLOBAL_DEFAULT_配置文件名
        if os.path.exists(GLOBAL_DEFAULT_配置文件名):
            config = configparser.ConfigParser()
            config.read(GLOBAL_DEFAULT_配置文件名)
            if config.has_section('settings'):
                # self.load_config()
                self.output_message(f"默认配置文件加载成功: {GLOBAL_DEFAULT_配置文件名}\n")
                # print(f"默认配置文件加载成功: {GLOBAL_DEFAULT_CONFIG_FILE}\n")
        else:
            self.output_message(f"默认配置文件不存在，使用默认全局变量:\n")
            # print(f"默认配置文件不存在，使用默认全局变量:\n")
        # self.print_config()

    async def load_config(self, widget):
        global GLOBAL_DEFAULT_转存计算上报轮询间隔, GLOBAL_DEFAULT_S50设备IP, \
            GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录, GLOBAL_DEFAULT_输出文件夹转存计算上报目录, \
            GLOBAL_DEFAULT_配置文件名, GLOBAL_DEFAULT_观测站ID, GLOBAL_DEFAULT_拍摄时长, GLOBAL_FLAG_是否是长期观测站, \
            GLOBAL_观测站和个人标识, GLOBAL_DEFAULT_个人标识ID, \
            GLOBAL_DEFAULT_拍摄exe文件名, GLOBAL_DEFAULT_转存exe文件名, GLOBAL_DEFAULT_计算上报exe文件名
        """加载用户指定的配置文件"""
        # config_file = self.config_file_input.value
        # config_file = await  toga.Window.open_file_dialog(self, title="选择配置文件ini", initial_directory=r'.', \
        #                                                   file_types=['ini'], multiple_select=False, \
        #                                                   on_result=None, multiselect=None)
        config_file = await  toga.Window.dialog( self,dialog= toga.OpenFileDialog(title="选择配置文件ini", initial_directory=r'.',file_types=['ini']) )
        if config_file != None:
            config_file = str(config_file)
            self.clear_all_logs(widget)
            self.output_message(str(type(config_file)))
            # time.sleep(0.1)
            if os.path.exists(config_file):
                GLOBAL_DEFAULT_配置文件名 = config_file
                self.config_file_input.value = GLOBAL_DEFAULT_配置文件名
                config = configparser.ConfigParser()
                config.read(config_file,encoding='GBK')
                self.output_message(f"配置文件包含如下：{config.sections()}")
                if config.has_section('settings'):
                    islongterm = config.get('settings', 'is_LongTerm', fallback=GLOBAL_FLAG_是否是长期观测站)
                    if islongterm == 'True':
                        GLOBAL_FLAG_是否是长期观测站 = True
                    else:
                        GLOBAL_FLAG_是否是长期观测站 = False
                    self.is_longterm_station_switch.value = GLOBAL_FLAG_是否是长期观测站
                    GLOBAL_观测站和个人标识 = config.get('settings', 'station', fallback=GLOBAL_观测站和个人标识)
                    GLOBAL_DEFAULT_观测站ID = config.get('settings', 'station_prefix', fallback=GLOBAL_DEFAULT_观测站ID)
                    self.station_id_input.value = GLOBAL_DEFAULT_观测站ID
                    GLOBAL_DEFAULT_个人标识ID = config.get('settings', 'person_id', fallback=GLOBAL_DEFAULT_个人标识ID)
                    self.person_id_input.value = GLOBAL_DEFAULT_个人标识ID
                    self.onchange_is_longterm_station_switch(widget)
                    GLOBAL_DEFAULT_S50设备IP = config.get('settings', 'device_ip', fallback=GLOBAL_DEFAULT_S50设备IP)
                    self.ip_input.value = GLOBAL_DEFAULT_S50设备IP
                    GLOBAL_DEFAULT_转存计算上报轮询间隔 = int(
                        config.get('settings', 'wait_time', fallback=GLOBAL_DEFAULT_转存计算上报轮询间隔))
                    self.waittime_togatext.value = GLOBAL_DEFAULT_转存计算上报轮询间隔
                    GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录 = config.get('settings', 'input_folder',
                                                                            fallback=GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录)
                    self.input_path_togatext.value = GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录
                    GLOBAL_DEFAULT_输出文件夹转存计算上报目录 = config.get('settings', 'output_folder',
                                                                           fallback=GLOBAL_DEFAULT_输出文件夹转存计算上报目录)
                    self.output_path_togatext.value = GLOBAL_DEFAULT_输出文件夹转存计算上报目录
                    GLOBAL_DEFAULT_拍摄时长 = config.get('settings', 'duration_time', fallback=GLOBAL_DEFAULT_拍摄时长)
                    self.capture_duration_togatext.value = GLOBAL_DEFAULT_拍摄时长
                    GLOBAL_DEFAULT_拍摄exe文件名 = config.get('settings', 'capture_exe_file',
                                                              fallback=GLOBAL_DEFAULT_拍摄exe文件名)
                    self.exename_capture_togatext.value = GLOBAL_DEFAULT_拍摄exe文件名
                    GLOBAL_DEFAULT_转存exe文件名 = config.get('settings', 'transfer_exe_file',
                                                              fallback=GLOBAL_DEFAULT_转存exe文件名)
                    self.exename_transfer_togatext.value = GLOBAL_DEFAULT_转存exe文件名
                    GLOBAL_DEFAULT_计算上报exe文件名 = config.get('settings', 'reporter_exe_file',
                                                                  fallback=GLOBAL_DEFAULT_计算上报exe文件名)
                    self.exename_reporter_togatext.value = GLOBAL_DEFAULT_计算上报exe文件名
                    print(f"配置文件加载成功: {config_file}\n")
                    self.output_message(f"配置文件加载成功: {config_file}\n")

                else:
                    print(f"配置文件加载失败: {config_file}，使用默认程序配置吧\n")
                    self.output_message(f"配置文件加载失败: {config_file}，使用默认程序配置吧\n")
            else:
                print(f"配置文件不存在: {config_file}\n")
                self.output_message(f"配置文件不存在: {config_file}\n")
            self.print_config()

    async def save_config(self, widget):
        global GLOBAL_观测站和个人标识, GLOBAL_DEFAULT_转存计算上报轮询间隔, GLOBAL_DEFAULT_S50设备IP, GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录,\
            GLOBAL_DEFAULT_输出文件夹转存计算上报目录, GLOBAL_DEFAULT_配置文件名, GLOBAL_DEFAULT_观测站ID,GLOBAL_DEFAULT_拍摄时长
        """保存当前配置到指定文件"""
        GLOBAL_观测站和个人标识 = f'{GLOBAL_DEFAULT_观测站ID}{GLOBAL_DEFAULT_个人标识ID}'
        config_file = self.config_file_input.value
        config_file = await  toga.Window.save_file_dialog(self, title="保存配置文件ini", suggested_filename='S50.ini',
                                                          file_types=['ini'], on_result=None)
        print(config_file)
        config = configparser.ConfigParser()
        config['settings'] = {
            'station': GLOBAL_观测站和个人标识,
            'station_prefix': GLOBAL_DEFAULT_观测站ID,
            'is_LongTerm': str(GLOBAL_FLAG_是否是长期观测站),
            'person_id': GLOBAL_DEFAULT_个人标识ID,
            'filter': 'IRCUT',
            'other': 'S50',
            'device_ip': GLOBAL_DEFAULT_S50设备IP,
            'duration_time': GLOBAL_DEFAULT_拍摄时长,
            'wait_time': GLOBAL_DEFAULT_转存计算上报轮询间隔,
            'input_folder': GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录,
            'output_folder': GLOBAL_DEFAULT_输出文件夹转存计算上报目录,
            'capture_exe_file': GLOBAL_DEFAULT_拍摄exe文件名,
            'transfer_exe_file': GLOBAL_DEFAULT_转存exe文件名,
            'reporter_exe_file': GLOBAL_DEFAULT_计算上报exe文件名,
        }
        config['B1'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['B2'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['G1'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['G2'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['R1'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['R2'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['g1'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['g2'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['r1'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['r2'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['i1'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['i2'] = {
            'target_coords': 'T CrB,0,0;C1,0,0;C2,0,0;C3,0,0;D1,0,0;D2,0,0',
        }
        config['IRCUT1'] = {
            # 'target_coords': 'T CrB,602,986;C1,614,1242;C2,821,1262;C3,973,961;D1,299,1497;D2,636,332',#Q3
            'target_coords': 'T CrB,589,1063;C1,584,1320;C2,789,1353;C3,960,1062;D1,253,1554;D2,664,413', #Q4
        }
        config['IRCUT2'] = {
            # 'target_coords': 'T CrB,223,706;C1,218,963;C2,423,996;C3,595,706;D1,0,0;D2,299,56',#Q3
            'target_coords': 'T CrB,564,1044;C1,612,1288;C2,820,1279;C3,927,968;D1,337,1576;D2,505,409', #Q4
        }
        with open(config_file, 'w',encoding='GBK') as f:
            config.write(f)
        self.output_message(f"配置文件已保存到: {config_file}\n")
        GLOBAL_DEFAULT_配置文件名 = config_file
        # self.load_config(widget)
        # self.output_message(f"重新加载已保存的配置文件: {config_file}\n")
    def clear_all_logs(self, widget):
        self.output_area.value = ''

    def start_capture_thread(self, widget):
        global GLOBAL_DEFAULT_S50设备IP, GLOBAL_DEFAULT_TCRB赤经RA, GLOBAL_DEFAULT_TCRB赤纬DEC, GLOBAL_DEFAULT_拍摄时长, GLOBAL_DEFAULT_拍摄exe文件名
        if True: #self.thread_flag_capture == False: #此处逻辑有点儿问题，懒得调试了，就这样强制启动好了
            self.thread_flag_capture = True
            self.output_message(f'正在开始拍摄进程\n')
            cmd = 'start   \"01拍摄\" '
            cmd += f' {GLOBAL_DEFAULT_拍摄exe文件名} {GLOBAL_DEFAULT_S50设备IP} T_CrB {GLOBAL_DEFAULT_TCRB赤经RA} {GLOBAL_DEFAULT_TCRB赤纬DEC} 0 {GLOBAL_DEFAULT_拍摄时长} 1 1 1 1 \n'
            cmd += f'pause\n'
            self.process_capture = subprocess.Popen(cmd, shell=True)
            print(cmd, self.process_capture)
        else:
            self.output_message(f'已有拍摄进程，请先停止拍摄\n')

    def stop_capture_thread(self, widget):
        global GLOBAL_DEFAULT_拍摄exe文件名
        if True:
            self.thread_flag_capture = False
            try:
                self.output_message(f'正在终止拍摄进程{self.process_capture.pid}\n')
                subprocess.call(['taskkill', '/F', '/PID', str(self.process_capture.pid)])
                subprocess.call(['taskkill', '/F', '/im', os.path.basename(GLOBAL_DEFAULT_拍摄exe文件名)])
            except:
                pass
            self.output_message(f'拍摄进程已停止\n')

    def start_transfer_thread(self, widget):
        global GLOBAL_DEFAULT_S50设备IP, GLOBAL_DEFAULT_转存exe文件名, GLOBAL_DEFAULT_转存计算上报轮询间隔, GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录, GLOBAL_DEFAULT_输出文件夹转存计算上报目录
        if True:#self.thread_flag_transfer == False:
            self.thread_flag_capture = True
            self.output_message(f'正在开始转存进程\n')
            cmd = 'start   \"02转存\" '
            cmd += f'{GLOBAL_DEFAULT_转存exe文件名} --waittime {GLOBAL_DEFAULT_转存计算上报轮询间隔} --input {GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录}  --output {GLOBAL_DEFAULT_输出文件夹转存计算上报目录} \n'
            cmd += f'pause\n'
            self.process_transfer = subprocess.Popen(cmd, shell=True)
            print(cmd, self.process_transfer)
        else:
            self.output_message(f'已有转存进程，请先停止\n')

    def stop_transfer_thread(self, widget):
        global GLOBAL_DEFAULT_转存exe文件名
        if True:
            try:
                self.thread_flag_transfer = False
                self.output_message(f'正在转存拍摄进程{self.process_transfer.pid}\n')
                subprocess.call(['taskkill', '/F', '/PID', str(self.process_transfer.pid)])
                subprocess.call(['taskkill', '/F', '/im', os.path.basename(GLOBAL_DEFAULT_转存exe文件名)])
            except:
                pass
            self.output_message(f'转存进程已停止\n')

    def start_report_thread(self, widget):
        global GLOBAL_DEFAULT_S50设备IP, GLOBAL_DEFAULT_TCRB赤经RA, GLOBAL_DEFAULT_TCRB赤纬DEC, GLOBAL_DEFAULT_拍摄时长, \
            GLOBAL_DEFAULT_计算上报exe文件名, GLOBAL_DEFAULT_配置文件名, GLOBAL_DEFAULT_输出文件夹转存计算上报目录,\
            GLOBAL_观测站和个人标识,GLOBAL_DEFAULT_观测站ID,GLOBAL_DEFAULT_个人标识ID
        if True:#self.thread_flag_report == False:
            self.thread_flag_capture = True
            self.output_message(f'{GLOBAL_观测站和个人标识} 使用{GLOBAL_DEFAULT_配置文件名}配置文件\n正在开始计算上报进程\n')
            cmd = 'start   \"03计算上报\" '
            if str(GLOBAL_DEFAULT_个人标识ID).strip() == '':
                cmd += f'{GLOBAL_DEFAULT_计算上报exe文件名} --station {GLOBAL_DEFAULT_观测站ID}  --config {GLOBAL_DEFAULT_配置文件名} --dir {GLOBAL_DEFAULT_输出文件夹转存计算上报目录} \n'
            else:
                cmd += f'{GLOBAL_DEFAULT_计算上报exe文件名} --station {GLOBAL_DEFAULT_观测站ID} --personid {GLOBAL_DEFAULT_个人标识ID} --config {GLOBAL_DEFAULT_配置文件名} --dir {GLOBAL_DEFAULT_输出文件夹转存计算上报目录} \n'
            cmd += f'pause\n'
            self.process_reporter = subprocess.Popen(cmd, shell=True)
            print(cmd, self.process_reporter)
        else:
            self.output_message(f'已有计算上报进程，请先停止\n')

    def stop_report_thread(self, widget):
        global GLOBAL_DEFAULT_计算上报exe文件名
        if True:
            try:
                self.thread_flag_report = False
                self.output_message(f'正在终止计算上报进程{self.process_reporter.pid}\n')
                subprocess.call(['taskkill', '/F', '/PID', str(self.process_reporter.pid)])
                subprocess.call(['taskkill', '/F', '/im', os.path.basename(GLOBAL_DEFAULT_计算上报exe文件名)])
            except:
                pass
            self.output_message(f'计算上报进程已停止\n')

    def start_all_threads(self, widget):
        # self.start_capture_thread(widget)
        self.start_transfer_thread(widget)
        self.start_report_thread(widget)
        self.start_capture_thread(widget)
    def stop_all_threads(self, widget):
        self.stop_capture_thread(widget)
        self.stop_transfer_thread(widget)
        self.stop_report_thread(widget)
        self.thread_flag_capture = False
        self.thread_flag_transfer = False
        self.thread_flag_report = False

    async def choose_input_folder(self, widget):
        """选择输入文件夹"""
        folder = await toga.Window.select_folder_dialog(self, title="选择输入文件夹")
        if folder:
            global GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录
            GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录 = folder  # 选择第一个文件夹
            self.input_path_togatext.value = GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录
            self.output_message(f"选择的输入文件夹: {GLOBAL_DEFAULT_输入文件夹S5保存fit文件目录}\n")

    async def choose_output_folder(self, widget):
        """选择输出文件夹"""
        folder = await toga.Window.select_folder_dialog(self, title="选择输出文件夹")
        if folder:
            global GLOBAL_DEFAULT_输出文件夹转存计算上报目录
            # self.output_message(f"选择的输出文件夹: {folder}\n")
            GLOBAL_DEFAULT_输出文件夹转存计算上报目录 = folder  # 选择第一个文件夹
            self.output_path_togatext.value = GLOBAL_DEFAULT_输出文件夹转存计算上报目录
            self.output_message(f"选择的输出文件夹: {GLOBAL_DEFAULT_输出文件夹转存计算上报目录}\n")

    async def choose_exe_capture_file(self, widget):
        """选择拍摄exe"""
        filename = await toga.Window.open_file_dialog(self, title="选择拍摄exe",file_types=['exe'])
        if filename:
            global GLOBAL_DEFAULT_拍摄exe文件名
            GLOBAL_DEFAULT_拍摄exe文件名 = filename  # 选择第一个文件夹
            self.exename_capture_togatext.value = GLOBAL_DEFAULT_拍摄exe文件名
            self.output_message(f"选择的拍摄exe: {GLOBAL_DEFAULT_拍摄exe文件名}\n")

    async def choose_exe_transfer_file(self, widget):
        """选择转存exe"""
        filename = await toga.Window.open_file_dialog(self, title="选择转存exe",file_types=['exe'])
        if filename:
            global GLOBAL_DEFAULT_转存exe文件名
            GLOBAL_DEFAULT_转存exe文件名 = filename  # 选择第一个文件夹
            self.exename_transfer_togatext.value = GLOBAL_DEFAULT_转存exe文件名
            self.output_message(f"选择的转存exe: {GLOBAL_DEFAULT_转存exe文件名}\n")

    async def choose_exe_reporter_file(self, widget):
        """选择计算上报exe"""
        filename = await toga.Window.open_file_dialog(self, title="选择计算上报exe",file_types=['exe'])
        if filename:
            global GLOBAL_DEFAULT_计算上报exe文件名
            GLOBAL_DEFAULT_计算上报exe文件名 = filename  # 选择第一个文件夹
            self.exename_reporter_togatext.value = GLOBAL_DEFAULT_计算上报exe文件名
            self.output_message(f"选择的计算上报exe: {GLOBAL_DEFAULT_计算上报exe文件名}\n")


def main():
    return tcrb_S50_gui()


if __name__ == '__main__':
    main().main_loop()
